<template>
  <div class="cms-article-container layout-padding">
    <el-card shadow="hover" class="layout-padding-auto">
      <div class="cms-article-search mb15">
        <el-tree-select
            v-model="searchState.search.orgId"
            :data="loadState.sysOrgData"
            :render-after-expand="true"
            :default-expanded-keys="defaultExpandedKeys"
            style="width: 500px"
            check-strictly
            filterable
            @change="orgChange"
        />
        <el-input size="default" placeholder="请输入文章标题" v-model="bannerDesc" class="ml10"
                  style="margin-right:5px;max-width: 200px; height: 40px"></el-input>
        <el-button size="default" type="primary" class="ml10" @click="getTableData">
          <el-icon>
            <ele-Search/>
          </el-icon>
          查询
        </el-button>
        <el-button size="default" type="success" class="ml10" @click="onOpenAdd('add')">
          <el-icon>
            <ele-FolderAdd/>
          </el-icon>
          新增
        </el-button>
      </div>
      <el-table :data="state.tableData.data" v-loading="state.tableData.loading" style="width: 100%">
        <el-table-column type="index" label="序号" width="60"/>
        <el-table-column prop="bannerTitle" label="轮播图标题" show-overflow-tooltip></el-table-column>
        <el-table-column prop="bannerUrl" label="轮播图" show-overflow-tooltip>
          <template #default="scope">
            <el-image
                style="width: 200px; height: 100px"
                :src="scope.row.bannerUrl"
                :preview-src-list="[scope.row.bannerUrl]"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="bannerDisable" label="发布状态" width="120" show-overflow-tooltip>
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.bannerDisable==0">已发布</el-tag>
            <el-tag type="info" v-else>停止发布</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="bannerPriority" label="优先级" width="120" show-overflow-tooltip></el-table-column>
        <el-table-column prop="gmtCreate" label="创建时间" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" width="300">
          <template #default="scope">
            <el-button  size="small" type="primary"
                       @click="onOpenEdit('edit', scope.row)">修改
            </el-button>
            <el-button  size="small" type="warning"
                       @click="onRowTopping(scope.row)">置顶
            </el-button>
            <el-button  v-if="scope.row.bannerDisable==0" size="small"
                       type="info" @click="onRowStopPublish(scope.row)">停止发布
            </el-button>
<!--            :disabled="scope.row.userName === 'admin'"-->
            <el-button  v-if="scope.row.bannerDisable==1" size="small"
                       type="primary" @click="onRowPublish(scope.row)">重新发布
            </el-button>
            <el-button size="small" type="danger"
                       @click="onRowDel(scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          @size-change="onHandleSizeChange"
          @current-change="onHandleCurrentChange"
          class="mt15"
          :pager-count="5"
          :page-sizes="[100, 200, 500]"
          v-model:current-page="state.tableData.param.pageNum"
          background
          v-model:page-size="state.tableData.param.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="state.tableData.total"
      >
      </el-pagination>
    </el-card>
    <BannerDialog ref="BannerDialogRef"
                  @refresh="getTableData()"
                  :orgId="searchState.search.orgId"
                  :orgTree="loadState.sysOrgData"
    />
  </div>
</template>

<script setup lang="ts" name="articleIndex">
import {defineAsyncComponent, reactive, onMounted, ref} from 'vue';
import {ElMessageBox, ElMessage} from 'element-plus';
import {systemApi} from "/@/api/system";
import {useBannerApi} from "/@/api/cms/banner";

const {listByPage, add, edit, removeById, topping, shelf} = useBannerApi();
const {orgTree, orgAreaTree} = systemApi();
// 引入组件
const BannerDialog = defineAsyncComponent(() => import('/src/views/cms/banner/dialog.vue'));
const bannerDesc = ref('');
// 定义变量内容
const BannerDialogRef = ref();
const defaultExpandedKeys = ref<string[]>([]); // 新增默认展开的节点
const state = reactive<CmsArticleState>({
  tableData: {
    data: [],
    total: 0,
    loading: false,
    param: {
      pageNum: 1,
      pageSize: 10,
    },
  },
});

const searchState = ref<any>({
  search: {
    orgId: '',
  }
});
const loadState = ref<any>({
  sysOrgData: [],
  channelTreeData: [],
});

const orgChange = (val: string) => {
  if (val) {
    searchState.value.search.orgId = val;
    getTableData();
  }
}

// 初始化表格数据
const getTableData = async () => {
  state.tableData.loading = true;
  const data = [];
  const res = await listByPage({
    current: state.tableData.param.pageNum,
    pageSize: state.tableData.param.pageSize,
    bannerDesc: bannerDesc.value,
    orgId: searchState.value.search.orgId,
  });
  if (res.status === 200) {
    data.push(...res.data.records);
  }
  state.tableData.data = data;
  state.tableData.total = res.data.total;
  state.tableData.loading = false;
};

const loadOrgTree = async () => {
  const res = await orgAreaTree();
  if (res.status === 200) {
    loadState.value.sysOrgData = res.data;
    // 设置默认展开的节点为第一个节点的ID
    if (loadState.value.sysOrgData.length > 0) {
      defaultExpandedKeys.value = [loadState.value.sysOrgData[0].id];
    }
  }
};

// 打开新增弹窗
const onOpenAdd = (type: string) => {
  BannerDialogRef.value.openDialog(type);
};
// 打开修改弹窗
const onOpenEdit = (type: string, row: RowCmsBannerType) => {
  console.log('edit', row.orgId)
  BannerDialogRef.value.openDialog(type, row);
};

// 置顶
const onRowTopping = (row: RowCmsBannerType) => {
  ElMessageBox.confirm(`确定要置顶名称为：${row.bannerTitle}的文章吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    const res = await topping({
      id: row.id
    })
    if (res.status === 200) {
      ElMessage.success('置顶成功');
      await getTableData();
    } else {
      ElMessage.error('置顶失败');
    }
  })
}

/**
 * 停止发布
 * @param row
 */
const onRowStopPublish = (row: RowCmsBannerType) => {
  ElMessageBox.confirm(`确定要 停止发布 名称为：${row.bannerTitle}的文章吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    const res = await shelf({
      id: row.id,
      shelfOp: 1,
    })
    if (res.status === 200) {
      ElMessage.success('停止发布成功');
      await getTableData();
    } else {
      ElMessage.error('停止发布失败');
    }
  })
}

const onRowPublish = async (row: RowCmsBannerType) => {
  const res = await shelf({
    id: row.id,
    shelfOp: 0,
  })
  if (res.status === 200) {
    ElMessage.success('重新发布成功');
    await getTableData();
  } else {
    ElMessage.error('重新发布失败');
  }
}

// 删除
const onRowDel = (row: RowCmsBannerType) => {
  ElMessageBox.confirm(`确定要删除标题为：“${row.bannerTitle}的应用吗？”，是否继续?`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    const res = await removeById({id: row.id})
    if (res.status === 200) {
      await getTableData();
      ElMessage.success('删除成功');
    }
  })
      .catch(() => {
      });
};
// 分页改变
const onHandleSizeChange = (val: number) => {
  state.tableData.param.pageSize = val;
  getTableData();
};
// 分页改变
const onHandleCurrentChange = (val: number) => {
  state.tableData.param.pageNum = val;
  getTableData();
};
// 页面加载时
onMounted(async () => {
  await loadOrgTree();
});
</script>

<style scoped lang="scss">
.system-user-container {
  :deep(.el-card__body) {
    display: flex;
    flex-direction: column;
    flex: 1;
    overflow: auto;

    .el-table {
      flex: 1;
    }
  }
}
</style>
